//CourseController.java
package org.example.demo3.controller;

import org.example.demo3.model.Course;
import org.example.demo3.model.Teacher;
import org.example.demo3.service.CourseService;
import org.example.demo3.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/Course")
public class CourseController {
    @Autowired
    CourseService courseService;
    @Autowired
    TeacherService teacherService;

    //返回课程列表
    @RequestMapping("list")
    public String list(Model model) {
        List<Course> courses = courseService.findAll();
        model.addAttribute("courses", courses);
        return "CoursesList";
    }

    //添加课程
    @RequestMapping("add")
    public String add(Course course){
        courseService.add(course);
        return "redirect:/Course/list/1/3";
    }

    //删除课程
    @RequestMapping("remove")
    public String remove(int id){
        courseService.remove(id);
        return "redirect:/Course/list/1/3";
    }

    //准备添加课程&获取教师列表
    @RequestMapping("toAdd")
    public String toAdd(Model model){
        return "addCourse";
    }

    //准备修改 & 查询对应id的课程
    @RequestMapping("toEdit")
    public String toEdit(int id, Model model){
        // 获取当前课程信息
        Course oldCourse = courseService.findOneById(id);
        model.addAttribute("course", oldCourse);

        // 获取所有教师列表
        List<Teacher> teachers = teacherService.findAll();
        model.addAttribute("teachers", teachers);
        return "editCourse";
    }

    //修改课程
    @RequestMapping("edit")
    public String edit(Course course){
        courseService.edit(course);
        return "redirect:/Course/list/1/3";
    }

    //分页显示
    @RequestMapping("list/{currentPage}/{pageSize}")
    public String list(Model model, @PathVariable("currentPage") int currentPage, @PathVariable("pageSize") int pageSize) {
        if(currentPage < 1) currentPage = 1;
        if(pageSize < 1) pageSize = 10;
        List<Course> courses = courseService.findByPage(currentPage,pageSize);
        model.addAttribute("courses", courses);
        return "CoursesList";
    }

}
